package JZ_Offer.dataStructure.tree;

import base.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * 二叉树的深度
 * <p>
 * 输入一棵二叉树，求该树的深度。从根结点到叶结点依次经过的结点（含根、叶结点）形成树的一条路径，最长路径的长度为树的深度。
 * <p>
 * 输入：
 * {1,2,3,4,5,#,6,#,#,7}
 * 返回值：
 * 4
 */
public class JZ55_二叉树的深度 {

    /**
     * 递归获取
     */
    public static int TreeDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = TreeDepth(root.left);
        int right = TreeDepth(root.right);
        int result = 1 + (left > right ? left : right);
        return result;
    }

    /**
     * 层次遍历
     */
    public static int TreeDepth1(TreeNode root) {
        if (root == null) {
            return 0;
        }

        int count = 0;
        List<TreeNode> treeNodes = new ArrayList<>();
        treeNodes.add(root);
        while (treeNodes.size() > 0) {
            count++;
            List<TreeNode> levelNodes = new ArrayList<>();
            for (TreeNode node : treeNodes) {
                if (node.left != null) {
                    levelNodes.add(node.left);
                }
                if (node.right != null) {
                    levelNodes.add(node.right);
                }
            }
            treeNodes = levelNodes;
        }
        return count;
    }


    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        TreeNode l = new TreeNode(2);
        TreeNode r = new TreeNode(3);
        TreeNode ll = new TreeNode(4);
        root.left = l;
        root.right = r;
        l.left = ll;
        int depth = TreeDepth1(root);
        System.out.println(depth);
    }
}
